package com.wuge.cart.interceptor;

import com.wuge.cart.to.UserInfoTo;
import com.wuge.common.to.MemberTo;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class UserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> localUser=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MemberTo loginUser = (MemberTo)request.getSession().getAttribute("loginUser");
        UserInfoTo userInfoTo=new UserInfoTo();
        if (loginUser!=null){
            userInfoTo.setUserId(loginUser.getId());
            String userKey = getUserKey(request,response);
            if (userKey==null){
                userKey=createUserKeyAndReturn(response);
            }
            userInfoTo.setUserKey(userKey);
        }else{
            userInfoTo.setTempUser(true);
            userInfoTo.setUserId(loginUser.getId());
            String userKey = getUserKey(request,response);
            if (userKey==null){
                userKey=createUserKeyAndReturn(response);
            }
            userInfoTo.setUserKey(userKey);
        }
        localUser.set(userInfoTo);
        return true;
    }
    public String getUserKey(HttpServletRequest request,HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("gulimallSession")){
                cookie.setMaxAge(30*60*1000);
                cookie.setDomain("gulimall.com");
                response.addCookie(cookie);
                return cookie.getValue();
            }
        }
        return null;
    }
    public String createUserKeyAndReturn(HttpServletResponse response){

        String uuid=UUID.randomUUID().toString();
        Cookie userKey = new Cookie("gulimallSession", uuid);
        userKey.setDomain("gulimall.com");
        userKey.setMaxAge(30*60*1000);
        response.addCookie(userKey);
        return uuid;
    }
}
